import {createRouter, createWebHashHistory, createWebHistory} from 'vue-router'

import TextPractice from "@/views/practice/text-practice/Index.vue";
import Index from  '@/views/index/Index.vue'
import HomeView from "@/views/home/HomeView.vue";
import LetterPractice from "@/views/practice/letter-practice/Index.vue";
import GamePractice from "@/views/practice/game-practice/Index.vue";
import HomeIndex from "@/views/home/Index.vue";
import Test from "@/views/Test.vue";
import PrimaryTeach from "@/views/teach/primary/Index.vue";
import SchemeSquare from "@/views/scheme-square/Index.vue"
import Error404 from "@/views/error/404/Index.vue"
import {getToken} from "@/utils/TokenUtil";
import Login from "@/views/user/Login.vue";
const routes = [
  {
    path: '/',
    name: 'index',
    component: Index,
  },
  {
    path: '/test',
    name: 'test',
    component: Test
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    children:[
      {
        path: 'index',
        name: 'home-index',
        component: HomeIndex
      },
      {
        path: 'practice/text',
        name: 'text-practice',
        component: TextPractice
      },
      {
        path: 'practice/letter',
        name: 'letter-practice',
        component: LetterPractice
      },
      {
        path: 'practice/game',
        name: 'game-practice',
        component: GamePractice
      },
      {
        path: 'teach/primary',
        name: 'teach-primary',
        component:PrimaryTeach
      },
      {
        path: 'scheme/square',
        name: 'scheme-square',
        component:SchemeSquare
      },
    ]
  },
  {
    path: '/error/404',
    name: '404',
    component: Error404
  },

]

const router = createRouter({
  history: createWebHashHistory("/tw"),
  routes
})
router.beforeEach((to, from, next)=>{
  // 检查是否存在404
  if (to.matched.length === 0) {
    next("/error/404")
  }
  // 检查token
  if (to.meta.check) {

    let token = getToken();
    if (token) {
      // 登录了
      next()
    } else {
      // 未登录
      alert("请先登录")
      next("/login")
    }
  }
  next()
})
export default router
